import * as XLSX from 'xlsx';

// 列名映射处理函数
// const mapColumns = (data: ExcelRow[], mappings: ColumnMapping[]): ExcelRow[] => {
//   return data.map(row => {
//     const newRow: ExcelRow = {};
//     mappings.forEach(mapping => {
//       if (row[mapping.original] !== undefined) {
//         newRow[mapping.unified] = row[mapping.original];
//       }
//     });
//     return newRow;
//   });
// };

// 增强合并逻辑
// const mergeByField = (
//   dataList: ExcelRow[][], 
//   mergeField: string, 
//   mappings: FileMappingConfig[]
// ): ExcelRow[] => {
//   const mergedMap = new Map<string, ExcelRow>();
//   dataList.forEach((fileData, fileIndex) => {
//     const mappedData = mapColumns(fileData, mappings[fileIndex].mappings);
//     mappedData.forEach(row => {
//       const key = row[mergeField]?.toString() || '';
//       mergedMap.set(key, { ...mergedMap.get(key), ...row });
//     });
//   });
//   return Array.from(mergedMap.values());
// };

// 修改后的 mergeData 函数（支持多文件合并）
const mergeData = (dataList: ExcelRow[][], mergeField: string): ExcelRow[] => {
  const mergedMap = new Map<string, ExcelRow>();
  // 遍历所有文件的数据
  dataList.forEach(fileData => {
    fileData.forEach(row => {
      const key = row[mergeField]?.toString() || '';
      mergedMap.set(key, { ...mergedMap.get(key), ...row }); // 合并冲突字段
    });
  });

  return Array.from(mergedMap.values());
};

// 数据去重逻辑
const dedupeData = (data: ExcelRow[], dedupeField: string): ExcelRow[] => {
  const seen = new Set();
  return data.filter(row => {
    const value = row[dedupeField]?.toString() || '';
    return seen.has(value) ? false : seen.add(value);
  });
};

// 新增批量修改逻辑
const modifyData = (data: ExcelRow[], rules: ModifyRule[]): ExcelRow[] => {
  return data.map(row => {
    const newRow = { ...row };
    rules.forEach(rule => {
      const value = newRow[rule.field];
      switch (rule.type) {
        case 'replace':
          if (value === rule.config.oldValue) {
            newRow[rule.field] = rule.config.newValue!;
          }
          break;
        case 'calculate':
          try {
            // 使用 Function 安全执行公式
            newRow[rule.field] = new Function('value', `return ${rule.config.formula}`)(value);
          } catch (error) {
            console.error('计算错误:', error);
          }
          break;
        case 'format':
          if (typeof value === 'number' && rule.format === 'currency') {
            newRow[rule.field] = `$${value.toFixed(2)}`;
          }
          // 可扩展其他格式化规则
          break;
      }
    });
    return newRow;
  });
};

self.onmessage = (e: MessageEvent<WorkerMessage>) => {
  const { type, data, fileName, mergeField, dedupeField, sendTime } = e.data;
  // 记录接收到消息的时间
  const receiveTime = performance.now();
  try {
    switch (type) {
      case 'parse': {
        const parsedWorkbook  = XLSX.read(data, { type: 'array' });
        const sheet = parsedWorkbook .Sheets[parsedWorkbook .SheetNames[0]];
        const jsonData: ExcelRow[] = XLSX.utils.sheet_to_json(sheet);
        self.postMessage({ 
          type: 'parse', 
          data: jsonData, 
          merges: sheet['!merges'] || [],
          fileName,
          sendTime,
          receiveTime,
        });
        break;
      }

      case 'merge': {
        const merged = mergeData(data, mergeField!);
        self.postMessage({ type:'merge', data: merged, sendTime, receiveTime });
        break;
      }

      case 'freeMerge': {
        const freeMerge = mergeData(data, mergeField!);
        self.postMessage({ type: 'merge', data: freeMerge, sendTime, receiveTime });
        break;
      }

      case 'dedupe': {
        const deduped = dedupeData(data, dedupeField!);
        self.postMessage({ type: 'dedupe', data: deduped, sendTime, receiveTime });
        break;
      }

      case 'modify': {
        const modified = modifyData(data, e.data?.rules!);
        self.postMessage({ type: 'modify', data: modified, sendTime, receiveTime });
        break;
      }
      case 'export': {
        const worksheet = XLSX.utils.json_to_sheet(data);
        const exportWorkbook  = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(exportWorkbook , worksheet, 'Sheet1');
        const buffer = XLSX.write(exportWorkbook , { type: 'array', bookType: 'xlsx' });
        self.postMessage({ type: 'export', data: buffer, fileName, sendTime, receiveTime });
        break;
      }
    }
  } catch (error: any) {
    self.postMessage({ type: 'error', error: error.message });
  }
};